package com.xiaoc.bulldozer.controller;


import com.google.common.collect.Maps;
import com.xc.framework.common.exception.BusinessException;
import com.xiaoc.bulldozer.common.ConfigKeys;
import com.xiaoc.bulldozer.common.Constant;
import com.xiaoc.bulldozer.common.ResponseCode;
import com.xiaoc.bulldozer.common.dto.BannerQueryDto;
import com.xiaoc.bulldozer.common.dto.FinancialProductQueryDto;
import com.xiaoc.bulldozer.common.dto.WeixinUserDto;
import com.xiaoc.bulldozer.common.model.*;
import com.xiaoc.bulldozer.common.service.*;
import com.xiaoc.bulldozer.common.service.cache.CommonConfigCacheService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping(value = "/index")
public class IndexController extends BulldozerFrontBaseController {

    private Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Resource(name = "financialProductService")
    private FinancialProductService financialProductService;

    @Resource(name = "awardService")
    private AwardService awardService;

    @Resource(name = "commonConfigService")
    private CommonConfigCacheService commonConfigService;

    @Resource(name = "accountService")
    private AccountService accountService;
    
    @Resource(name = "bannerService")
    private BannerService bannerService;

    @Resource(name = "awardTimeRuleService")
    private AwardTimeRuleService awardTimeRuleService;

    @Resource(name = "advertiseService")
    private AdvertiseService advertiseService;

    @GetMapping(value = "/getPictures")
    public ModelAndView getPictures() {

        Map<String, Object> picturesMap = new HashMap<>();

        picturesMap.put("defaultWxAwardBigUrl", commonConfigService.getValue(ConfigKeys.INDEX_SHOW_AWARD_PIC));

        return renderJson("picture/picture.json", picturesMap);
    }

    /**
     * 首页初始化-获取移动产品列表
     */
    @RequestMapping(value = "/init")
    public ModelAndView init() {
        try {
             FinancialProductQueryDto financialProductQueryDto = new FinancialProductQueryDto();
             financialProductQueryDto.setPage(1);

            financialProductQueryDto.setStatus(Constant.ENABLE);

            List<FinancialProduct> financialProductList = financialProductService.getFinancialProductListByCondition(financialProductQueryDto);

            Map<String, Object> paramMap = new HashMap<>(15);
            paramMap.put("productList", financialProductList);
//            paramMap.put("happyFamilyPictureUrl", commonConfigService.getValue(ConfigKeys.HAPPY_FAMILY_PICTURE_URL));
            paramMap.put("homeBgImg", commonConfigService.getValue(ConfigKeys.HOME_BG_IMG));

            return renderJson("index/index.json", paramMap);
        } catch (Exception e) {
            logger.error("index/init error", e);
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(), "系统异常");
        }
    }

    /**
     *  获取产品详情
     * @param id 产品id
     * @return
     */
    @RequestMapping(value = "/getFinancialProductDetail")
    public ModelAndView getFinancialProductDetail(@RequestParam String productId) {

        if (StringUtils.isBlank(productId)) {
            logger.warn("ID为空");
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(), "该产品已下架");
        }

        FinancialProduct financialProduct = financialProductService.getAllFinancialProductByStatusOrProductId(productId);

        if (financialProduct == null) {
            logger.warn("产品不存在");
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(), "该产品已下架");
        }

        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("id", financialProduct.getId());
        paramMap.put("name", financialProduct.getName());
        paramMap.put("detailImgUrl", financialProduct.getDetailImgUrl());
        return renderJson("index/cmProductDetail.json", paramMap);
    }
    
    /**
     * 首页顶部滚动视图初始化
     */
    @RequestMapping(value = "/topInit")
    public ModelAndView topInit(@RequestBody BannerQueryDto bannerQueryDto) {
        try {
            if (bannerQueryDto.getPage() == null) {
                bannerQueryDto.setPage(1);
            }
            bannerQueryDto.setBannerType(Constant.BANNER_TYPE.INDEX);
            bannerQueryDto.setBannerStatus(Constant.ENABLE);
            List<Banner> bannerList = bannerService.getBannerListByCondition(bannerQueryDto);
            
            Banner banner = new Banner();
            banner.setTitle(commonConfigService.getValue(ConfigKeys.INDEX_BANNER_TITLE));
            banner.setBannerUrl(commonConfigService.getValue(ConfigKeys.INDEX_BANNER_URL));
            banner.setBannerDetailUrl("");
            
            bannerList.add(0, banner);
            
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("bannerList", bannerList);
            return renderJson("index/banner.json", paramMap);
        } catch (Exception e) {
            logger.error("index/banner error", e);
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(), "系统异常");
        }
    }

    /**
     * 获取横幅详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/topDetail")
    public ModelAndView topDetail(@RequestParam Integer id) {

        Banner banner = bannerService.getBannerById(id);

        if (banner == null ) {
            logger.info("没有横幅信息");
            throw new BusinessException(ResponseCode.FAIL.getCode(), ResponseCode.FAIL.getMsg());
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("productId", banner.getId());
        paramMap.put("bannerDetailUrl", banner.getBannerDetailUrl());
        paramMap.put("buttonUrl", banner.getButtonUrl());
        paramMap.put("buttonText", banner.getButtonText());
        paramMap.put("title", banner.getTitle());
        return renderJson("index/topDetail.json", paramMap);
    }
    /**
     * 获取活动结束按钮信息
     */
    @RequestMapping(value = "/buttonInfo")
    public ModelAndView buttonInfo() {
        try {
            AwardTimeRule awardTimeRule = awardTimeRuleService.getAwardTimeRuleByCurrentTime1();
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("buttonUrl", commonConfigService.getValue(ConfigKeys.AWARD_STOP_BUTTON_URL));
            paramMap.put("buttonText", commonConfigService.getValue(ConfigKeys.AWARD_STOP_BUTTON_TEXT));
            if (awardTimeRule!=null) {
                paramMap.put("tip", awardTimeRule.getTip());
            }

            return renderJson("index/buttonInfo.json", paramMap);
        } catch (Exception e) {
            logger.error("index/buttonInfo error", e);
            throw new BusinessException(ResponseCode.BUSINESS_ERROR.getCode(), "系统异常");
        }
    }

    @GetMapping(value = "/getCurrentDate")
    public ModelAndView getCurrentDate() {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("currentDate", System.currentTimeMillis());
        return renderJson("index/currentDate.json", paramMap);

    }

    /**
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "/share")
    public ModelAndView share(@RequestParam String type) {

        if (StringUtils.isBlank(type)) {
            return jsonFailed(ResponseCode.NOT_SHARE.getCode(),ResponseCode.NOT_SHARE.getMsg());
        }
        List<Advertise> advertises = advertiseService.getAdvertiseList(type);
        Integer size = advertises.size();

        if (size <= 0) {
            logger.info("分享未开启 type = {}", type);
            return jsonFailed(ResponseCode.NOT_SHARE.getCode(),ResponseCode.NOT_SHARE.getMsg());
        }
        Random random = new Random();
        Integer num = random.nextInt(size);
        Advertise advertise = advertises.get(num);
        WeixinUserDto weixinUserDto = getCurrentWeixinUserDto();

        Map<String, Object> params = Maps.newHashMap();
        params.put("parentUserId", weixinUserDto.getId());
        params.put("shareText", advertise.getTitle());
        params.put("shareImg", advertise.getImgUrl());

        return renderJson("advertise/share.json", params);
    }

    @RequestMapping(value = "/getValue")
    public ModelAndView getValue(@RequestParam String key) {

        Map<String, Object> params = Maps.newHashMap();
        params.put("value", commonConfigService.getValue(ConfigKeys.AWARD_RULE_DESC));

        return renderJson("index/configValue.json", params);
    }

}
